package org.hang.gift.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.hang.exception.BusinessException;
import org.hang.exception.ResponseCode;
import org.hang.exception.RonghuaAssert;
import org.hang.gift.clients.GiftClient;
import org.hang.gift.domain.GoodsSku;
import org.hang.gift.domain.ShopCar;
import org.hang.gift.dto.AddShopCarDTO;
import org.hang.gift.dto.UpdateNumDTO;
import org.hang.gift.dto.UpdateSelectDTO;
import org.hang.gift.mapper.ShopCarMapper;
import org.hang.gift.service.IShopCarService;
import org.hang.util.AjaxResult;
import org.hang.util.TenantIdName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hang
 * @since 2024-06-11
 */
@Service
public class ShopCarServiceImpl_one extends ServiceImpl<ShopCarMapper, ShopCar> implements IShopCarService {

    @Autowired
    private GiftClient giftClient;

    @Override
    public void addShopCar(AddShopCarDTO dto) {
        // 1 参数校验
        // 1.1 非空校验
        RonghuaAssert.isNotNull(dto.getSkuId(), ResponseCode.RESPONSE_CODE_500);

        // 2 根据skuId和userId查询购物车表,看该用户有没有添加过该商品
        Wrapper<ShopCar> wrapper = new EntityWrapper<ShopCar>()
                .eq("sku_id", dto.getSkuId())
                .and()
                .eq("user_id", dto.getUserId());
        ShopCar shopCar = selectOne(wrapper);

        // 3 如果该用户已经添加过该商品,则直接修改数量即可
        if(Objects.nonNull(shopCar)){
            // 修改后的数量 = 原本的数量 + 本次添加的数量
            shopCar.setNum(shopCar.getNum()+dto.getNum());
            shopCar.setUpdateTime(new Date());
            updateById(shopCar);
        }else{
            // 4 如果没有添加过
            // 4.1 远程调用礼物服务,根据skuId获取商品的详情信息
            AjaxResult ajaxResult = giftClient.get(dto.getSkuId());
            if(!ajaxResult.isSuccess()){
                throw new BusinessException(ajaxResult.getMessage());
            }
            String s = JSONObject.toJSONString(ajaxResult.getResultObj());
            GoodsSku goodsSku = JSONObject.parseObject(s, GoodsSku.class);

            // 4.2 根据商品信息构建购物车对象
            ShopCar car = new ShopCar();
            car.setSpuId(goodsSku.getSpuId());
            car.setSpuName(goodsSku.getSpuName());
            car.setSkuId(goodsSku.getId());
            car.setSkuInfo(goodsSku.getSkuName());
            car.setAddPrice(goodsSku.getPrice());
            car.setPrice(goodsSku.getPrice());
            car.setUserId(dto.getUserId());
            car.setUsername(dto.getUsername());
            car.setTenantId(goodsSku.getTenantId());
            car.setTenantName(goodsSku.getTenantId()+"");
            car.setSelect(true);    // 在新增的时候,状态默认就是选中的
            car.setCreateTime(new Date());
            car.setNum(dto.getNum());

            // 4.3 将购物车添加到数据库
            insert(car);
        }
    }

    @Override
    public void updateNum(UpdateNumDTO updateNumDTO) {
        RonghuaAssert.isNotNull(updateNumDTO.getSkuId(),ResponseCode.RESPONSE_CODE_500);
        Wrapper<ShopCar> wrapper = new EntityWrapper<ShopCar>()
                .eq("sku_id", updateNumDTO.getSkuId())
                .and()
                .eq("user_id", updateNumDTO.getUserId());
        ShopCar shopCar = selectOne(wrapper);
        RonghuaAssert.isNotNull(shopCar,ResponseCode.RESPONSE_CODE_50001);
        shopCar.setNum(updateNumDTO.getNum());
        shopCar.setUpdateTime(new Date());
        updateById(shopCar);
    }

    @Override
    public void updateSelect(UpdateSelectDTO updateSelectDTO) {
        RonghuaAssert.isNotNull(updateSelectDTO.getSkuId(),ResponseCode.RESPONSE_CODE_500);
        Wrapper<ShopCar> wrapper = new EntityWrapper<ShopCar>()
                .eq("sku_id", updateSelectDTO.getSkuId())
                .and()
                .eq("user_id", updateSelectDTO.getUserId());
        ShopCar shopCar = selectOne(wrapper);
        RonghuaAssert.isNotNull(shopCar,ResponseCode.RESPONSE_CODE_50001);
        shopCar.setSelect(updateSelectDTO.getSelect());
        shopCar.setUpdateTime(new Date());
        updateById(shopCar);
    }

    /**
     * 购物车分组展示
     * @return
     */
    @Override
    public Map<TenantIdName, List<ShopCar>> listGroup(Long Id) {
        List<ShopCar> shopCars = selectList(new EntityWrapper<ShopCar>().eq("user_id", Id));
        if(shopCars == null || shopCars.size() == 0){
            return null;
        }
        Map<TenantIdName, List<ShopCar>> listMap = shopCars.stream().collect(Collectors.groupingBy(x ->
                new TenantIdName(x.getTenantId(), x.getTenantName())));
        return listMap;
    }

    @Override
    public void syncData() {

    }


}
